//@ts-nocheck
import React, { useRef, useState } from 'react'
import {
  XFlow,
  XFlowCanvas,
  CanvasContextMenu,
  // FlowchartExtension,
  // FlowchartCanvas,
  // FlowchartNodePanel,
  /** Graph的扩展交互组件 */
  CanvasSnapline,
  CanvasNodePortTooltip,
  DagGraphExtension,
  CanvasScaleToolbar,
  CanvasMiniMap,
  CanvasToolbar
} from '@antv/xflow'

import type { IAppLoad, NsGraph } from '@antv/xflow'

import {
  useCmdConfig,
  useGraphHookConfig,
  useMenuConfig,
  useToolbarConfig
} from './config'

import { NodePanel, FormPanel, ScriptPanel } from './partials'
import { initGraph } from './utils'
import styles from './index.module.less'

interface FlowProps {
  data: NsGraph.IGraphData
}

const Flow: React.FC<FlowProps> = props => {
  const { data } = props
  const cmdConfig = useCmdConfig()
  const graphHooksConfig = useGraphHookConfig()
  const menuConfig = useMenuConfig(props)
  const toolbarConfig = useToolbarConfig(props)

  const formPanelRef = useRef()
  const ScriptPanelRef = useRef()

  const openScriptDraw = script => {
    ScriptPanelRef.current.initDraw(script)
  }

  const onLoad: IAppLoad = async app => {
    const graph = await app.getGraphInstance()
    graph.on('node:click', ({ node }) => {
      const nodeData: NsGraph.INodeConfig = node.getData()
      formPanelRef.current.initDraw(nodeData)
    })
    // graph.on('blank:click', () => {
    //   formPanelRef.current.close()
    // })
    // 布局
    await initGraph(app, data)
  }
  return (
    <XFlow
      onLoad={onLoad}
      hookConfig={graphHooksConfig}
      commandConfig={cmdConfig}
      className={styles['xflow-workspace']}
    >
      <DagGraphExtension /* layout="LR" */ />
      <CanvasToolbar
        layout="horizontal"
        config={toolbarConfig}
        position={{ top: 0, left: 290, right: 0, height: 40 }}
      />
      <XFlowCanvas
        position={{
          top: 0,
          bottom: 0,
          left: 290,
          right: 0
        }}
      >
        {/** 工具栏 */}
        <CanvasScaleToolbar position={{ top: 60, left: 10 }} />
        {/** 小地图  */}
        <CanvasMiniMap minimapOptions={{ width: 200, height: 120 }} />
        <CanvasContextMenu config={menuConfig} />
        <CanvasSnapline />
        <CanvasNodePortTooltip />
        <FormPanel ref={formPanelRef} openScriptDraw={openScriptDraw} />
      </XFlowCanvas>
      <NodePanel position={{ top: 0, bottom: 0, left: 0, width: 290 }} />
      <ScriptPanel ref={ScriptPanelRef} />
    </XFlow>
  )
}
export default Flow
